<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="staffPhoto" :src="staffPhoto" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress
        v-if="showProgress"
        type="line"
        :percentage="percentage"
        status="success"
        :stroke-width="6"
        class="progress"
      ></el-progress>
    </el-upload>
  </div>
</template>

<script>
// 导入cos的SDK调用
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDpT0HI3WieIfiY7QSCfsnSrypPhiSv72h', // 身份识别ID
  SecretKey: 'PWMvDI8j7F8mCNJ0SgfPuBD0YsxnOkrl' // 身份秘钥
})
export default {
  name: 'UploadImg',
  props: {
    staffPhoto: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      // imageUrl: '',
      // 展示进度条
      showProgress: false,
      // 进度长度
      percentage: 0
    }
  },
  methods: {
    /* 使用自定义行为覆盖默认上传，注意一旦设置自定义上传行为之后，
    所有的上传操作都需要自己实现，比如数据处理，上传成功之后的后续操作，on-success钩子函数也不会继续触发 */
    upload (params) {
      // 上传文件开启进度条
      this.showProgress = true
      // 拿到file对象
      // console.log(params.file)
      cos.putObject({
        Bucket: 'yisir-1308304336', /* 必须 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          // console.log(JSON.stringify(progressData.percent))
          // this.percentage = JSON.stringify(progressData.percent) * 100
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        // 请求成功的回调
        console.log(err)
        if (data.statusCode === 200) { // 腾讯云cos请求成功返回一个地址 带上协议把地址存到img中
          // console.log(data)
          setTimeout(async () => {
            // this.imageUrl = `https://${data.Location}`
            // 子传父改变简单数据类型
            this.$emit('update:staffPhoto', `https://${data.Location}`)

            // 图片上传成功后隐藏进度条并且清空进度
            this.showProgress = false
            this.percentage = 0
          }, 800)
        }
      })
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
/* .progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #fff;
} */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
